#include "FreeTableDlg.h"

FreeTableDlg::FreeTableDlg(QWidget *parent) :
    QDialog(parent)//, bEmpty(false)
{
    setupUi(this);
    setModal(true);
    bEmpty = false;
    lcdElapsedTime->setDigitCount(8);
    lcdElapsedTime->display("00:00:00");
}

void FreeTableDlg::setItems(QMap<QString, QDateTime> items)
{
    freeTable = items;
    dateTime = QDateTime(QDate::currentDate(), QTime(0, 0, 0));
    ///
    bEmpty = false;
    if (!freeTable.isEmpty())   bEmpty = true;
    lstwFreeTables->clear();
    QMapIterator<QString, QDateTime> i(freeTable);
    QStringList tables;
    while(i.hasNext())
    {
        i.next();
        tables << i.key();
    }
    lstwFreeTables->addItems(tables);
}

//void FreeTableDlg::finalize()
//{
//    qDebug() << "f1" << lstwFreeTables->currentItem();
//    lstwFreeTables->setCurrentItem(0);
//    lstwFreeTables->clearSelection();
//    qDebug() << "f2" << lstwFreeTables->currentItem();
//}

QDateTime FreeTableDlg::calculateElapsedDateTime(QDateTime initDateTime, int &elapsedMinutes)
{
    int iTime = initDateTime.secsTo(QDateTime::currentDateTime());
    elapsedMinutes  = iTime/60;    /// de segundos a minutos
//    qDebug() << "iTime mins =" << iElapsedTime;
    QDateTime elapsedTime(QDate::currentDate(), QTime(0, 0, 0));
    QDateTime finalTime;
    finalTime = elapsedTime.addSecs(iTime);
    return finalTime;
}

void FreeTableDlg::terminarSlot()
{
    QString mesa = "";
    if (lstwFreeTables->currentItem() == 0)
        mesa = "Mesa 0";
    else
        mesa = lstwFreeTables->currentItem()->text();

//    qDebug() << QString("%1 < %2 < %3").arg(mesa).arg(time).arg("c");
    emit terminateFreeTable(mesa, iElapsedTime);
}

void FreeTableDlg::showLcdDisplay()
{
//    qDebug() << lstwFreeTables->currentItem();
    if (bEmpty && lstwFreeTables->currentItem() != 0)
    {
//        qDebug() << "dateTime =" << dateTime;
        elapsedTime = calculateElapsedDateTime(dateTime, iElapsedTime);
//        qDebug() << " min:" << elapsedTime.time().
        lcdElapsedTime->display(elapsedTime.time().toString("hh:mm:ss"));
    }
}

void FreeTableDlg::selectItemSlot(QListWidgetItem *item)
{
    QString table = item->text();
    dateTime = freeTable.value(table);
//    qDebug() << table << "|" << dateTime;
    showLcdDisplay();
}
